package com.ruoyi.tenant.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.tenant.dto.request.RequestUpdatePasswordDto;
import com.ruoyi.tenant.entity.BusinessEntity;
import com.ruoyi.tenant.entity.SysDeptEntity;
import com.ruoyi.tenant.entity.SysUserEntity;
import com.ruoyi.tenant.mapper.SysDeptDao;
import com.ruoyi.tenant.mapper.SysUserDao;
import com.ruoyi.tenant.service.SysUserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 系统用户
 *
 * @date 2016年9月18日 上午9:46:09
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysDeptDao sysDeptDao;
    @Override
    public List<String> queryAllPerms(Long userId) {
        return sysUserDao.queryAllPerms(userId);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return sysUserDao.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String username) {
        return sysUserDao.queryByUserName(username);
    }

    @Override
    public SysUserEntity queryObject(Long userId) {
        return sysUserDao.queryObject(userId);
    }

    @Override
    public List<SysUserEntity> queryList(Map<String, Object> map) {
    	List<SysUserEntity> queryList = sysUserDao.queryList(map);
    	for (int i=0;i<queryList.size();i++) {
			Date creatTime = queryList.get(i).getCreateTime();
			DateFormat dFormatPay = new SimpleDateFormat("yyyy-MM-dd");
			String format = dFormatPay.format(creatTime);
			queryList.get(i).setCreateTimes(format);
		}
        return queryList;
    }

    @Override
    public List<SysUserEntity> queryAdmins(Long deptId) {
        List<Long> longs = new ArrayList<Long>();

        if (deptId != null) {
            // 得到所有部门
            List<SysDeptEntity> sysDeptEntities = sysDeptDao.getDepts();

            // 父级部门
            addParentId(deptId, sysDeptEntities, longs);

            // 下级部门
            addSonId(deptId, sysDeptEntities, longs);

            longs.add(deptId);
        }

        return sysUserDao.queryAdmins(longs);
    }


    private void addParentId(Long deptId, List<SysDeptEntity> sysDeptEntities, List<Long> longs) {
        // 得到本部门的所有上级部门
        for (SysDeptEntity s : sysDeptEntities) {
            if (s.getDeptId().equals(deptId)) {
                if (null != s.getParentId() && s.getParentId() != 1) {
                    longs.add(s.getParentId());
                    addParentId(s.getParentId(), sysDeptEntities, longs);
                }
            }
        }
    }

    private void addSonId(Long deptId, List<SysDeptEntity> sysDeptEntities, List<Long> longs) {
        // 得到本部门的所有下级部门
        for (SysDeptEntity s : sysDeptEntities) {
            if (s.getParentId().equals(deptId)) {
                longs.add(s.getDeptId());
                addSonId(s.getDeptId(), sysDeptEntities, longs);
            }
        }
    }


    @Override
    public int queryTotal(Map<String, Object> map) {
        return sysUserDao.queryTotal(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserEntity user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        sysUserDao.save(user);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        }
        sysUserDao.update(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] userId) {
        sysUserDao.deleteBatch(userId);
    }

    @Override
    public int updatePassword(Long userId, String password, String newPassword) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("password", password);
        map.put("newPassword", newPassword);
        return sysUserDao.updatePassword(map);
    }

    @Override
    public Map<String, String> getFormatUserName(SysUserEntity user) {
        SysUserEntity sysUser = sysUserDao.getSysUser(user);
        String company = "";
        if (sysUser != null) {
            company = sysUser.getCompanyName();
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("company", company);
        return map;
    }

    @Override
    public SysUserEntity getSysUserByMobile(String mobile) {
        SysUserEntity sysUserEntity = sysUserDao.getSysUserByMobile(mobile);
        return sysUserEntity;
    }

    @Override
    public void register(SysUserEntity register) {
        register.setStatus(1);
        register.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        register.setPassword(new Sha256Hash(register.getPassword(), salt).toHex());
        register.setSalt(salt);
        register.setUsername(register.getMobile());
        sysUserDao.register(register);
    }

    @Override
    public List<Map<String, Object>> getApartmentOperatorType() {
        return null;
    }


    @Override
    public int updatePasswordByMobile(Long userId, String newPassword) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("newPassword", newPassword);
        return sysUserDao.updatePasswordByMobile(map);
    }

    @Override
    public void updateUser(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        }
        sysUserDao.update(user);

    }

    @Override
    public BusinessEntity getBusinessInfoByUserId(Long userId) {
        return null;
    }


    /**
     * 
    * @Description: 修改登录密码 
    * @param @param requestUpdatePasswordDto 参数  
    * @return 返回值说明
     */
	@Override
	@Transactional
	public void updateUserPassword(RequestUpdatePasswordDto pdatePasswordDto) {
		logger.info("updateUserPassword修改登录密码   Start...！");
		SysUserEntity sysEntiry = new SysUserEntity();

		// 设置新密码（加密）
		logger.info("----  修改登录密码   入参 :{}",JSON.toJSONString(sysEntiry));
		sysUserDao.updateUserPassword(sysEntiry);
		logger.info("updateUserPassword修改登录密码   END...！");
	}

}
